var express = require("express");
const { v4: uuidv4 } = require("uuid");
const md5 = require("md5");
var dbConfig = require('../utils/dbconfig')
var router = express.Router();
var { jwtAuth, createToken } = require("../controllers/tokenControl");
var dbconfig = require("../utils/dbconfig");
var Response = require("../utils/response");

function login(req, res,next) {
  // let token = req.headers.token;
  // if (!token) res.send({ data: "用户未登录，请先登录", code: 0 });
  let { username, password } = req.body;
  // let username = "admin",
  //   password = "123456";
  console.log("用户名是：" + username, "密码是：" + password);

  if (!username || !password) {
    res.send({ data: "请输入账号或密码"});
    return;
  }
  var sql = `select * from base_user where username=? and password=?`;
  var sqlArr = [username,password];
  var callBack = (err, data) => {
    if (err) {
      console.log("连接出错了");
    } else {
      const token ="Bearer " + createToken({ username });
      if(token){
        
        // window.localStorage.setItem('token', token);
        console.log("token",token);
      }
      res.send(new Response(500, "查询成功", data));
      
      
    }
  };

  dbConfig.sqlConnection(sql, sqlArr, callBack);
};

function regUser(req, res, next) {
  // let eq = req;
  // console.log(req);
  // console.log(req.body,"------------",req.query);
  var {id,username,password,tel,realname,gender,birth,status,id_card,email,rank,position_no,department_id} = req.body;
  let sql = "INSERT INTO base_user (id,username,password,tel,realname,gender,birth,status,id_card,email,`rank`,`position_no`,`department_id`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
  var sqlArr = [id,username,password,tel,realname,gender,birth,status,id_card,email,rank,position_no,department_id];
  var callBack = (err, data) => {
    if (err) {
      console.log("连接出错了", err);
    } else {
      if (data.affectedRows == 1) {
        res.send(new Response(200, "注册成功", data));
        // console.log(sql);
      } else {
        res.send(new Response(500, "注册失败", data));
      }
    }
  };
  dbConfig.sqlConnection(sql, sqlArr, callBack);
}

module.exports = {
  login,regUser
}